package com.guiji.quartz.domain;

import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.task.DataSaveUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 不需要代理
 * @author: wangxw
 * @date 2021/12/16 14:22
 */
public class Kotaku {
	private static final Logger log = LoggerFactory.getLogger(Kotaku.class);
	private static final String baseUrl = "https://kotaku.com/culture/news";
	private static final String domain = "https://kotaku.com/culture";

	public static void mainMethod() throws Exception {

		HttpResponse response = null;
		try {
			response = HttpRequest.get(baseUrl)
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3194.4 Safari/537.36")
				.setConnectionTimeout(30000)
				.execute();

			if (null != response && response.getStatus() == 200) {
				List<HttpCookie> cookies = response.getCookies();
				String resp = response.body();
				Set<String> resUrl = getUrl(resp);
				getContent(resUrl, cookies);
			} else {
				log.error(baseUrl + String.valueOf(response.getStatus()));
			}

		} catch (Exception e) {
			log.error(String.format("访问 {} 失败", baseUrl) + e);
			return;
		}
	}


	private static void getContent(Set<String> listContent, List<HttpCookie> cookies) throws MalformedURLException, URISyntaxException, InterruptedException {
		List<Map> allNews = new ArrayList();
		for (String url : listContent) {
			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer(domain).append(url).toString();
			}
			if (null != cookies && cookies.size() > 0) {
				CookieManager ccm = new CookieManager();
				CookieStore CookieStore = ccm.getCookieStore();
				for (HttpCookie cookie : cookies) {
					URL domainUrl = new URL(domain);
					CookieStore.add(domainUrl.toURI(), cookie);
				}
				HttpRequest.setCookieManager(ccm);
			}

			log.info("listContent长度-{},getContent执行到-{}", listContent.size(), url);
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url)
					.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36")
					.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
					.header("Accept-Encoding", "gzip, deflate")
					.header("Refer", baseUrl)
					.setConnectionTimeout(30000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				String pattern = "<h1 class=\"sc-1efpnfq-0 biSEwE\">(.*?)</h1>";
				Pattern p = Pattern.compile(pattern);
				Matcher m = p.matcher(doc);
				if (m.find()) {
					title = m.group(1);
					if(null!=title){
						title = title.replaceAll("<.*?>","");
					}
				}

			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			StringBuffer content = new StringBuffer();
			String contentStr = null;
			try {
				String pattern = "\"articleBody\":\"(.*?)\",\"";
				Pattern p = Pattern.compile(pattern);
				Matcher m = p.matcher(doc);
				if (m.find()) {
					contentStr = m.group(1);
				}
				contentStr = contentStr.replace("\\n","$$$");
			} catch (Exception e) {
				continue;
			}

			int a = 0;
			try {
				String comment = ReUtil.findAll("Comments \\(.*?\\)",doc,0).get(0);
				a = Integer.parseInt(ReUtil.findAll("[0-9]{1,10}", comment, 0).get(0));
			} catch (Exception e) {
			}

			List<String> newImgs = new ArrayList<>();
			String img = null;
			try {
				String pattern = "data-srcset=\"(.*?) ";
				Pattern p = Pattern.compile(pattern);
				Matcher m = p.matcher(doc);
				if (m.find()) {
					img = m.group(1);
					newImgs.add(img);
				}

			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			} finally {
			}

			Date date = new Date();
			if (contentStr.length() > 50000 || contentStr.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				SpiderNews spiderNews = new SpiderNews();
				spiderNews.setNewsTitle(title);
				spiderNews.setNewsContent(contentStr);
				spiderNews.setNewsPicJson(JSONUtil.toJsonStr(newImgs));
				spiderNews.setNewsUrl(url);
				spiderNews.setNewsPublicTime(date);
				HashMap map = new HashMap();
				map.put("spidernews", spiderNews);
				map.put("hotData", a);
				allNews.add(map);
			} catch (Exception e) {
				continue;
			}
		}

		//对新闻热度排序
		Collections.sort(allNews, (o1, o2) -> (int) o2.get("hotData") - (int) o1.get("hotData"));
		int k = 10;
		if (allNews.size() < 10) {
			k = allNews.size();
		}
		for (int i = 0; i < k; i++) {
			Map map1 = allNews.get(i);
			SpiderNews sp = (SpiderNews) map1.get("spidernews");
			try {
				DataSaveUtil.saveData(sp.getNewsTitle(), sp.getNewsContent(), sp.getNewsPicJson(), sp.getNewsUrl(), sp.getNewsPublicTime(), baseUrl, "kotaku-Game");
				log.info(Thread.currentThread().getName() + "-----------------kotaku-Game ----------------");
			} catch (Exception e) {
				continue;
			}
		}
	}

	private static Set<String> getUrl(String content) {
		Set<String> res = new HashSet<>();

		//"itemListElement":
		String pattern = "\"itemListElement\":(.*?)}</script>";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		try {
			if (m.find()) {
				String temp = m.group(1);
				JSONArray jobjs = JSONUtil.parseArray(temp);
				if (jobjs != null && jobjs.size() > 0) {
					for (int k = 0; k < jobjs.size(); k++) {
						JSONObject jobj = (JSONObject) jobjs.get(k);
						String url = (String) jobj.get("url");
						res.add(url);
					}
				}

			}
		} catch (Exception e) {

		} finally {

		}

		return res;
	}


//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}

}




